package com.qf.sclg.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import java.util.HashMap;
import java.util.UUID;

/*
pom.xml
<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-core</artifactId>
  <version>4.5.16</version>
</dependency>
*/
public class SendSms {
    public static String Sms(String tel) {
//        设置访问的短信平台已授权用户信息
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI5t6McjfRcJBVuAuk86xR", "JbSV5YlPEDfDvgIfgYU5nzSXHivqbM");
        /** use STS Token
         * 模拟短信请求，向阿里云接口发送
         DefaultProfile profile = DefaultProfile.getProfile(
         "<your-region-id>",           // The region ID
         "<your-access-key-id>",       // The AccessKey ID of the RAM account
         "<your-access-key-secret>",   // The AccessKey Secret of the RAM account
         "<your-sts-token>");          // STS Toke
         **/
//        创建一个本地客户端（向短信平台发送请求）
        IAcsClient client = new DefaultAcsClient(profile);
//      创建请求，阿里云后台验证的固定信息
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
//        设置请求行为，不修改
        request.setSysAction("SendSms");

//        发送短信的动态参数
//        短信模板和签名
        request.putQueryParameter("SignName", "阳阳商城");
        request.putQueryParameter("TemplateCode", "SMS_205409285");

        request.putQueryParameter("PhoneNumbers", tel);

//        request.putQueryParameter("TemplateParam", "212143");
//
//        将随机的数字装换成json格式
        String code = UUID.randomUUID().toString().substring(0,5);
        HashMap<String,String> map = new HashMap<>();
        map.put("code",code);
        String s = JSONObject.toJSONString(map);
        request.putQueryParameter("TemplateParam",s);

        try {
            CommonResponse response = client.getCommonResponse(request);
            String rs= response.getData();
            JSONObject jsonObject = JSON.parseObject(rs);
//            code判断是否发送成功
            String result =(String) jsonObject.get("Code");
            if(result.equalsIgnoreCase("ok")){
//                将验证码发送给用户
                return  code;
            }else {
                return  null;
            }
        } catch (ServerException e) {
            e.printStackTrace();
            return  null;
        } catch (ClientException e) {
            e.printStackTrace();
            return  null;
        }

    }
}